/**
* 内嵌式树形表格，返回tr行数据
* @param config 树配置
* @param data 行数据数组
* @param tbodyObj 表格主题jQuery对象
*/
function treeTable(config, data, tbodyObj) {

    var exampleTableData = [
        {
            id: '86',
            name: '中国',
            parentId: '',
            childrens: [
                {
                    id: '010',
                    name: '北京',
                    parentId: '86',
                    childrens: [
                        {
                            id: '0101',
                            name: '朝阳区',
                            parentId: '010',
                            childrens: []
                        },
                        {
                            id: '0102',
                            name: '海淀区',
                            parentId: '010',
                            childrens: []
                        }
                    ]
                },
                {
                    id: '021',
                    name: '上海',
                    parentId: '86',
                    childrens: []
                },
                {
                    id: '022',
                    name: '天津',
                    parentId: '86',
                    childrens: []
                },
                {
                    id: '023',
                    name: '重庆',
                    parentId: '86',
                    childrens: []
                }
            ]
        }
    ];

    // 树形表格示例配置
    var exampleTableConfig = {
        rows: {
            key: 'id',  // 数据唯一标识
            parentKey: 'parentId',  // 数据父标识
            children: 'childrens',   // 数据子树集合
            icon: {
                column: '2',    // 展开关闭图标所在列
                opened: 'fa-angle-down',    // 打开时图标
                closed: 'fa-angle-right'    // 关闭时图标
            },
            indentSize: '4',    // 缩进大小，4个空格
            indentColumn: [ // 需要缩进的列，第1列和第二列
                '1',
                '2'
            ]
        },
        columns: [
            {
                value: [],
                converter: function(row) {  // 自动行号写法
                    return row;
                }
            },
            {
                value: [    // 数据不加修饰直接放入td中
                    'id'
                ]
            },
            {
                value: [    // 列数据值
                    'id',
                    'name'
                ],
                converter: function(value) {    // 列数据转换器
                    return value.id + ' - ' + value.name;
                }
            }
        ]
    };

    if (null === config || config === undefined){
        config = exampleTableConfig;
    }

    if (null === data || data === undefined){
        data = exampleTableData;
    }
    _treeTable(config, data, tbodyObj, '');
    expandMenuListener();

    // 树形渲染
    function _treeTable(config, data, tbodyObj, prefix) {
        $.each(data, function (i, item) {
            var preTag = '<i class="parent fa ' + config.rows.icon.closed + '"></i>&nbsp;&nbsp;';

            var childrens = item[config.rows.children];
            var parentKey = item[config.rows.parentKey];
            parentKey = parentKey === null || parentKey === undefined ? '' : parentKey;
            var trData = '<tr key="' + item[config.rows.key] + '" parent-key="' + parentKey + '"' + (parentKey === '' ? '' : ' hidden') + '>';
            $.each(config.columns, function(j, column) {
                if (null !== childrens && childrens.length > 0 && config.rows.icon.column - 1 === j){
                    trData += '<td style="cursor: pointer;">';
                }else {
                    trData += '<td>';
                }
                if (null !== config.rows.indentColumn && config.rows.indentColumn.length > 0){
                    $.each(config.rows.indentColumn, function(it, columnNum) {
                        if (columnNum === (j + 1).toString()){
                            trData += prefix;
                        }
                    });
                }
                if (null !== childrens && childrens.length > 0){
                    if (config.rows.icon.column === (j + 1).toString()){
                        trData += preTag;
                    }
                }else {
                    if (config.rows.icon.column === (j + 1).toString()){
                        trData += '&nbsp;&nbsp;&nbsp;';
                    }
                }
                if (column.converter === null || column.converter === undefined){
                    var paramData = '';
                    $.each(column.value, function(index, v) {
                        paramData += item[v];
                    });
                    trData += paramData + '</td>';
                }else{
                    var param = {};
                    if (getArgumentsList(column.converter).indexOf('row') !== -1){
                        param = ++i;
                    }else {
                        $.each(column.value, function(index, v) {
                            param[v] = item[v];
                        });
                    }
                    trData += column.converter(param) + '</td>';
                }
            });

            tbodyObj.append(trData + '</tr>');

            if (null !== childrens && childrens.length > 0){
                if (null === config.rows.indentSize || config.rows.indentSize === '' || config.rows.indentSize === undefined) {
                    config.rows.indentSize = 4;
                }
                var indent = '';
                for(var k = 0; k < config.rows.indentSize ; k++){
                    indent += '&nbsp;'
                }
                return _treeTable(config, childrens, tbodyObj, prefix + indent);
            }
        });
    }

    // 获取函数参数
    function getArgumentsList(func){
        var funcString = func.toString();
        var regExp =/function\s*\w*\(([\s\S]*?)\)/;
        if(regExp.test(funcString)){
        var argList = RegExp.$1.split(',');
            return argList.map(function(arg){
                return arg.replace(/\s/g,'');
              });
        }else{
            return []
        }
    }

    // 展开监听
    function expandMenuListener() {

        function openNext(parent, key, parentKey){
            if (parent.next().length !== 0){
                if (parent.next().attr('parent-key') !== parentKey){
                    if (parent.next().attr('parent-key') === key){
                        parent.next().slideDown();
                    }
                    openNext(parent.next(), key, parentKey);
                }
            }

        }
        function closeNext(parent, parentKey){
            if (parent.next().length !== 0){
                if (parent.next().attr('parent-key') !== parentKey){
                    parent.next().slideUp().find('i.' + config.rows.icon.opened).removeClass(config.rows.icon.opened).addClass(config.rows.icon.closed);
                    closeNext(parent.next(), parentKey);
                }
            }
        }
        $('.parent').parent().click(function() {
            var parent = $(this).parent();
            if ($(this).children().first().hasClass(config.rows.icon.closed)){
                $(this).children().first().removeClass(config.rows.icon.closed).addClass(config.rows.icon.opened);
                openNext(parent, parent.attr('key'), parent.attr('parent-key'));
            }else {
                $(this).children().first().removeClass(config.rows.icon.opened).addClass(config.rows.icon.closed);
                closeNext(parent, parent.attr('parent-key'));
            }
        });
    }
}